package pandora.bo.AVC;

import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import pandora.data.IGenericSearchDAO;
import pandora.data.IPriceDAO;
import pandora.data.IProductDAO;
import pandora.data.ISearchDAO;
import pandora.data.IStoreDAO;
import pandora.data.mysql.JDBCGenericSearchDAO;
import pandora.data.mysql.JDBCPriceDAO;
import pandora.data.mysql.JDBCProductDAO;
import pandora.data.mysql.JDBCSearchDAO;
import pandora.data.mysql.JDBCStoreDAO;
import pandora.dto.PriceDTO;
import pandora.dto.ProductDTO;
import pandora.dto.SearchDTO;
import pandora.dto.StoreDTO;

public class Search implements ISearch{
	

	//private SearchDTO search;
	private IPriceDAO price = new JDBCPriceDAO();
	private IGenericSearchDAO nameSearch = new JDBCGenericSearchDAO();
//	private List<StoreDTO> stores;
	private IStoreDAO st= new JDBCStoreDAO();
	private List<String> todos= new LinkedList<String>();
	private IProductDAO pr1= new JDBCProductDAO();
	private static Search s;
	
	public static synchronized Search getInstance() {
        if (s == null)
            s = new Search();
        return s;
    }
	
	
	
	public List<ProductDTO> selectAllProducts(){
		List<ProductDTO> ls1=pr1.selectAllProducts();
		return ls1;
		
		
		
	}
	

	public List<PriceDTO> GenericSearch (ProductDTO product){
		List<StoreDTO> stores =st.getAllStores();
		List<PriceDTO> priceAux = new LinkedList<PriceDTO>();
		PriceDTO pr1;
		for(StoreDTO s1: stores){
			pr1=price.selectPriceStoreProduct(s1, product);
			
			if(pr1.getProduct()!=null){
				priceAux.add(pr1);
			}
		} 
		Collections.sort(priceAux);
		
		
		
		return priceAux;
	}

	public SortedSet<PriceDTO> GenericSearch (String search){
		List<StoreDTO> stores = new LinkedList<StoreDTO>();
		SortedSet<PriceDTO> priceAux = new TreeSet<PriceDTO>();
		stores.addAll(st.getAllStores());
		IProductDAO pr1= new JDBCProductDAO();
		String aux;
		String priceId;
		String OIDProduct=pr1.selectOIDbyName(search);
		
		
		
		for(StoreDTO s: stores){
			String nif= s.getStoreNIF();
			todos.addAll(price.selectAllValidProducts(nif));
			for(String pr: todos){
				if(pr.equals(OIDProduct)){
					aux=pr;
					priceId=price.selectOIDOfPrice(nif, aux);
					priceAux.add(price.selectPrice(nif, priceId));
					
				}
			
			}
					
		}
		return priceAux;
	}
	
	public void insertSearch(ProductDTO product, String user, Date date){
		nameSearch.saveSearch(product, user, date);
		
		
		
	}
	

}
